<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 维护自己的工作项 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基础信息"></title-name>
          <custom-form :isEmit="false" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''" @selectOrg="selectOrg">
          </custom-form>
        </a-card>
        <a-card :bordered="false">
          <title-name title="考核清单"></title-name>
          <a-button v-if="editModel != 0" class="mb12" type="primary" icon="plus" @click="visible = true"
            >添加考核项</a-button
          >
          <s-table
            ref="table"
            tableLayout="fixed"
            size="default"
            rowKey="key"
            :columns="editModel == 0 ? columnsLook : columns"
            :data="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
            :showPagination="false"
          >
            <template slot="ownIndex" slot-scope="text, record,index">
              <div class="form-item">
                <BaseInput
                  disabled
                  v-if="record.checkTypeCode == 1003 || record.checkTypeCode == 1008 || record.checkTypeCode == 1014"
                  v-model="record.ownIndex"
                ></BaseInput>
                <span v-else-if="record.unit == '-'">{{ record.ownIndex }}</span>
                <BaseInputNumber
                  :disabled="record.checkTypeCode == 1006 || editModel == 0"
                  v-else-if="record.unit == '次'"
                  v-model="record.ownIndex"
                  @blur='changeZero(record.ownIndex,index)'
                ></BaseInputNumber>
              </div>
            </template>
            <template slot="score" slot-scope="text, record,index">
              <div class="form-item">
                <BaseInputNumber
                  :precision="2"
                  :disabled="editModel == 0"
                  v-if="record.checkTypeCode != 1003 && record.checkTypeCode != 1008"
                  v-model="record.score"
                  @blur='changeZeroScore(record.score,index)'
                ></BaseInputNumber>
              </div>
            </template>
            <template slot="operation" slot-scope="text, record, index">
              <a-popconfirm  title="是否要删除此行？" @confirm="handleRemove(index)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </s-table>
        </a-card>

        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            v-if="form.auditStatus == 5"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
            >保存</a-button
          >
          <a-button
            v-else
            class="button_right"
            type="primary"
            :loading="loadingBtn.DRAFT"
            @click="handleSubmit('DRAFT')"
            >保存草稿</a-button
          >
          <a-button
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
      <table-modal :checkList="form.checkList" :visible.sync="visible" @ok="ok"> </table-modal>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import api from '@/api/safetySupervision/base/inspectionTemplate.js'
import tableModal from './tableModal' // 弹窗
import moment from 'moment'
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '考核项目',
    dataIndex: 'checkType'
  },
  {
    title: '自定指标',
    dataIndex: 'ownIndex',
    scopedSlots: { customRender: 'ownIndex' }
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '扣分标准',
    dataIndex: 'deductPoints'
  },
  {
    title: '总分',
    dataIndex: 'score',
    scopedSlots: { customRender: 'score' }
  },

  {
    title: '操作',
    dataIndex: 'operation',
    width: '230px',
    scopedSlots: { customRender: 'operation' }
  }
]
const columnsLook = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '考核项目',
    dataIndex: 'checkType'
  },
  {
    title: '自定指标',
    dataIndex: 'ownIndex'
  },
  {
    title: '单位',
    dataIndex: 'unit'
  },
  {
    title: '扣分标准',
    dataIndex: 'deductPoints'
  },
  {
    title: '总分',
    dataIndex: 'score'
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    tableModal
  },
  data() {
    this.columns = columns
    this.columnsLook = columnsLook
    return {
      loading: false, // 加载控件
      visible: false, //弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      editModelDialog: '0', //弹框操作状态:0 查看;1 编辑;2 新增
      form: { checkMonth: '', checkList: [],projectId:null}, // 表单
      updateList: [], //修改的表格数组
      initData: {},
      id: '',

      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },

      rules: {
        checkMonth: [{ required: true, message: '请选择' }]
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.checkList || []
          })
        })
      },

      init: false, // 初始化控件
      titles: ['维护自己的工作项查看', '维护自己的工作项编辑', '维护自己的工作项新增'],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  async mounted() {
    this.$route.meta.title = ['维护自己的工作项查看', '维护自己的工作项编辑', '维护自己的工作项新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.getDetails()
    } else {
      this.getDefault()
      this.form.projectId = this.$userInfo().currentPost.projectId;
      this.$nextTick(() => {
        // 默认映射联系人为登陆人
        this.form.creatorName = this.$userInfo().name
        this.form.checkDept = this.$userInfo().currentPost.deptName
        this.form.checkPost = this.$userInfo().employee.posts.filter(
          (e) => e.code == this.$userInfo().currentPost.postCode
        )[0].name
        this.form.checkMonth = moment().format('YYYY-MM')
        this.init = true
      })
      this.initMonth()
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('safe_check_persion')
  },
  computed: {
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
          span: 16,
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
          statusSet:[1,2,3,4,5,6],
          isQueryProjecDetail: false
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   },
        //   change: () => {
        //     if (this.editModel == 2) {
        //       this.initMonth()
        //     }
        //   }
        // },

        {
          keyName: 'checkDept',
          type: 'BaseInput',
          disabled: true,
          label: '部门'
        },
        {
          keyName: 'checkPost',
          type: 'BaseInput',
          disabled: true,
          label: '岗位'
        },
        {
          keyName: 'creatorName',
          type: 'BaseInput',
          disabled: true,
          label: '姓名'
        },
        {
          keyName: 'checkMonth',
          type: 'a-month-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '月份',
          attrs: {
            valueFormat: 'YYYY-MM'
          }
        }
      ]
    }
  },
  methods: {
    selectOrg(val) {
      if(val.length > 1) {
        this.form.branchCompanyId = val[val.length - 2].orgId
      }
    },
    changeZero(e,index){
       if(e==0){
         this.$message.warning('不能输入0')
         this.form.checkList[index].ownIndex = null;
       }
    },
    changeZeroScore(e,index){
    if(e==0){
          this.$message.warning('不能输入0');
          this.form.checkList[index].score = null;
        }
    },
    initMonth() {
      this.loading = true
      // console.log(this.$userInfo.currentPost)
      api
        .listPerson2({
          userId: this.$userInfo().id,
          checkMonth: moment().format('YYYY-MM'),
          projectId: this.form.projectId
        })
        .then((res) => {
          this.loading = false
          if (res.data.length > 0) {
            this.form.checkMonth = moment().add(1, 'month').format('YYYY-MM')
          }

          return res
        })
    },
    ok(e) {
      console.log(e)

      e.forEach((i) => {
        i.type = 1
        delete i.id
      })
      this.form.checkList = this.form.checkList.concat(e)
      this.initTable()
      this.$refs.table.refresh()
    },
    initTable() {
      this.form.checkList.forEach((i) => {
        if (i.checkTypeCode == 1003 || i.checkTypeCode == 1008 || i.checkTypeCode == 1014) {
          i.ownIndex = '据实计分'
        } else if (i.unit == '-') {
          i.ownIndex = '-'
        } else if (i.checkTypeCode == 1006) {
          i.ownIndex = '1'
        }
      })
    },
    getDefault() {
      this.$refs.table.localLoading = true
      api.listPersonDetail({}).then((res) => {
        this.$refs.table.localLoading = false
        this.form.checkList = res.data
        this.initTable()
        this.$refs.table.refresh(true)
      })
    },

    // 删除
    handleRemove(idx) {
      this.form.checkList.splice(idx, 1)
      this.$refs.table.refresh(true)
    },

    getDetails() {
      this.loading = true

      api
        .getPerson({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
          this.$refs.table.loadData()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag1 = true
      let flag2 = true
      let total = 0
      this.$refs.ruleForm.validate((e) => {
        flag1 = e
      })
      this.form.checkList.forEach((e) => {
        if (e.checkTypeCode != 1003 && e.checkTypeCode != 1008) {
          if ((!e.ownIndex && e.ownIndex != 0) || (!e.score && e.score != 0)) {
            flag2 = false
          } else {
            total += e.score
            e.ownIndex = e.ownIndex + ''
          }
        }
      })
      if (!flag2) {
        this.$message.warning('请完善表格数据')
        return false
      }
      console.log(total)
      if (total != 100) {
        this.$message.warning('当前考核配置总分不等于100，请正确调整')
        return false
      }
      if (flag1 && flag2) {
        return true
      } else {
        this.$message.warning("请填写完所有必填项信息")
        return false
      }
    },
    okSubmit(status) {
      this.setProcessConfig = null;
      this.loading = true
      this.loadingBtn[status] = true

      let form = this.$clone(this.form)
      form.auditStatus = status
      form.employeeId = this.$userInfo().employee.id
      form.userId = this.$userInfo().id
      form.checkName = this.$userInfo().name
      let req = [api.updatePerson, api.addPerson][this.editModel - 1] // 根据操作切换url地址
      this.submitApprovalConfirm(status == 'SUBMITTED' ? this.processConfig : 6, (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      req(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          if(status =='SUBMITTED') {
            //提交时，返回id
              this.businessId = res.data.id;
              this.setProcessConfig = this.processConfig;
                return
            }else{
            this.$multiTab.close()
          }
        })
        .catch((err) => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      if (!this.form.checkMonth) {
        this.$message.warning('必须选择月份')
        return
      }
      this.okSubmit(status)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
